package thread;

public class SyncDemo {
    private static boolean success1 ;
    private static boolean success2 ;
    public static void main(String[] args) {
        Bank bank = new Bank();
        Thread t1 = new Thread(){
            public void run(){
                success1 = bank.getMoney(20000);
            }
        };
        Thread t2 = new Thread(){
            public void run(){
                success2 = bank.getMoney(20000);
            }
        };
        t1.start();
        t2.start();

        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        if (success1&&success2){
            System.out.println("卡bug成功取款");
        }else {
            System.out.println("只有一人取款成功");
        }
    }
}

class Bank{
   private int account = 20000; //某人的账户
    public boolean getMoney(int money){ // 取钱方法
        int account = getAccount(); //查询账户余额
        if(account >= money){
            account -= money;
            //在这里发生线程切换就有可能出现并发安全问题
            Thread.yield();// 主动让当前线程放弃本次剩余时间片，模拟执行到这就没时间了
            saveAccount(account); //保存账户余额
            return true; //允许出钞
        }
        return false; //拒绝出钞
    }

    private void saveAccount(int account) {
        this.account = account;
    }

    private int getAccount() {
        return account;
    }
}
